package infra

import (
	"context"
	"errors"

	"gitee.com/h2ob/base"
	"gitee.com/h2ob/infra/model"
	"github.com/uptrace/bun"
)

func getUidSeg() (*model.HUid, error) {
	var uidSegs []model.HUid
	err := gH2oDb.db.NewSelect().Model(&uidSegs).Where("minv < maxv - offset - 1").Scan(*gH2oDb.ctx)
	if err != nil || len(uidSegs) == 0 {
		if err == nil {
			err = errors.New("empty")
		}
		base.GLogger.Infof("Find error:%s", err)
		last := new(model.HUid)
		err = gH2oDb.db.NewSelect().Model(last).Order("minv DESC").Limit(1).Scan(*gH2oDb.ctx)
		if err != nil {
			base.GLogger.Infof("Find error:%s", err)
			last.Minv = base.GUID_MIN_START
		} else {
			last.Minv = last.Maxv
		}
		last.Maxv = last.Minv + base.GUID_SEG_SIZE
		last.Off = 0
		r, err := gH2oDb.db.NewInsert().Model(last).Column("minv", "offset", "maxv").Ignore().Exec(*gH2oDb.ctx)
		if err != nil {
			base.GLogger.Infof("Insert error:%s", err)
			return nil, err
		}
		//插入新的记录
		lid, _ := r.LastInsertId()
		ar, _ := r.RowsAffected()
		base.GLogger.Infof("R:%d:%d", lid, ar)
		if ar > 0 {
			return last, nil
		} else {
			return nil, err
		}
	}
	return &uidSegs[0], nil
}

func updateUidSeg(huid *model.HUid, tx bun.Tx, ctx context.Context) error {
	old := huid.Off
	huid.Off = huid.Off + 1
	r, err := tx.NewUpdate().Model(huid).Column("offset").Where("hid=?", huid.Hid).Where("offset=?", old).Exec(ctx)
	if err != nil {
		base.GLogger.Infof("Update error:%s", err)
		return err
	}
	ar, _ := r.RowsAffected()
	if ar > 0 {
		return nil
	}
	return errors.New("affect zero")
}

func addNewOpenUser(uid int, oid string, otype string, tx bun.Tx, ctx context.Context) error {
	huser := model.HOpenUser{Uid: uint64(uid), Oid: oid, Otype: otype}
	r, err := tx.NewInsert().Model(&huser).Column("oid", "uid", "otype").Ignore().Exec(ctx)
	if err != nil {
		base.GLogger.Infof("Insert error:%s", err)
	}
	ar, _ := r.RowsAffected()
	if ar > 0 {
		return nil
	}
	base.GLogger.Info("affect zero")
	return errors.New("affect zero")
}

func addNewUser2(huser *model.HUser, tx bun.Tx, ctx context.Context) error {
	r, err := tx.NewInsert().Model(huser).Column("uid", "nickname", "avatar").Ignore().Exec(ctx)
	if err != nil {
		base.GLogger.Infof("Insert error:%s", err)
	}
	ar, _ := r.RowsAffected()
	if ar > 0 {
		return nil
	}
	base.GLogger.Info("affect zero")
	return errors.New("affect zero")
}
